import { ref } from 'vue'
import { adapter, withIgnoreValid } from '@/request'
import type { RequestWrapper } from '@/core/interfaces/common'
import { pz360QueryByGet } from '@/core/api/pz-360'
import { message } from 'ant-design-vue'
import is from '@/utils/is'
import { useMainStore } from '@/store/useMainStore'

interface PZ360Data {
  expire_time: string
  name: string
  price: string
  status: string
  title: string
  type: string
}

interface Params {
  keywords: string[]
}

export default function getPz360PriceAskWords() {
  const service = adapter<RequestWrapper<any>>(withIgnoreValid)
  const loading = ref(false)
  const response = ref<PZ360Data[]>([])
  const mainStore = useMainStore()

  const fetch = (params: Params) => {
    const { url, method } = pz360QueryByGet()
    loading.value = true
    response.value = []

    return Promise.all(
      params.keywords.map((item) => {
        return service({
          config: {
            url,
            method,
            params: { keyword: item, userId: mainStore.userId }
          },
          callback: (res) => {
            const data = JSON.parse(res.data.data)
            if (data.errcode === '0') {
              response.value.push(...data.data)
            }
          },
          error: (err) => {
            if (is.error(err)) {
              message.error(err.message)
            }
          },
          done: () => {
            loading.value = false
          }
        })
      })
    )
  }

  return [response, fetch, loading] as const
}
